<template>
  <div class="container">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-table :data="roleList" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row v-for="(levelOne, indexOne) in scope.row.children" :key="levelOne.id" :class="['border-bottom', indexOne === 0 ? 'border-top': '', 'vcenter']">
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag size="normal" effect="dark" closable @close="removeRightsById(scope.row, levelOne.id)">{{ levelOne.authName }}</el-tag>
                  <i class="el-icon-caret-right" />
                </el-col>
                <!-- 渲染二、三级权限 -->
                <el-col :span="19">
                  <el-row v-for="(levelTwo , indexTwo) in levelOne.children" :key="levelTwo.id" :class="[indexTwo === 0 ? '': 'border-top', 'vcenter']">
                    <el-col :span="6">
                      <el-tag type="success" closable @close="removeRightsById(scope.row, levelTwo.id)">{{ levelTwo.authName }}</el-tag>
                      <i class="el-icon-caret-right" />
                    </el-col>
                    <el-col :span="18">
                      <el-tag v-for="levelThree in levelTwo.children" :key="levelThree.id" type="warning" closable @close="removeRightsById(scope.row, levelThree.id)">
                        {{ levelThree.authName }}
                      </el-tag>

                    </el-col>
                  </el-row>
                </el-col>

              </el-row>

            </template>
          </el-table-column>
          <el-table-column type="index" />
          <el-table-column label="角色名称" prop="roleName" />
          <el-table-column label="角色描述" prop="roleDesc" />
          <el-table-column>
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>

        </el-table>

      </el-row>

    </el-card>

    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
    >
      <!-- 树形控件 -->
      <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultKeys" />
      <span slot="footer">
        <el-button @click="setRightsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">确认</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      setRightsDialogVisible: false,
      // 所有权限数据
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认勾选项
      defaultKeys: [],
      // 当前即将分配角色的id
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败！')
        return
      }

      this.roleList = res.data
    },
    // 根据ID删除权限
    async removeRightsById(roles, rights) {
      const confirmResult = await this.$confirm('是否要删除该角色下的权限？', '提示', {
        center: true,
        closeOnClickModal: false,
        closeOnPressEscape: false
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        this.$message.info('已经取消删除')
        return
      }

      const { data: res } = await this.$http.delete(`roles/${roles.id}/rights/${rights}`)

      if (res.meta.status !== 200) {
        this.$message.info('取消权限失败！')
        return
      }

      // 想不懂为什么能够这样改变页面的值？？？
      roles.children = res.data
      // roles.children = []
    },
    // 获取分配权限列表
    async showSetRightsDialog(roles) {
      // 保存当前对话框的id
      this.roleId = roles.id

      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }

      this.rightsList = res.data

      // 赋值给 defaultKeys 前清空一次该数组
      // 否则每次点开该弹窗都会保留上次存入的权限id
      this.defaultKeys = []
      this.getLeafKeys(roles, this.defaultKeys)

      this.setRightsDialogVisible = true
    },
    // 通过递归获取角色下所有三级权限的ID，并保存到 defaultKeys 中
    getLeafKeys(node, arr) {
      // 如果当前节点不包含children，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin-top: 15px;
  margin-bottom: 15px;
}

.border-top {
  border-top: 1px solid #eee;
}

.border-bottom {
  border-bottom: 1px solid #eee;
}

.el-tag {
  margin-right: 5px;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
